package com.fengye.algorithms.huawei;

import java.util.*;

/**
 * https://www.nowcoder.com/practice/03ba8aeeef73400ca7a37a5f3370fe68?tpId=37&tqId=21250&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=
 * @Author fengye
 * @Date 2023/3/8 20:50
 **/
public class BrotherStr {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            int a = in.nextInt();
            String[] strs = new String[a];
            for(int i = 0; i < a;i++) {
                strs[i] = in.next();
            }
            String str = in.next();
            int num = in.nextInt();
            List<String> brothers = findBrothers(strs, str);
            System.out.println(brothers.size());
            if(brothers.size() > num) {
                System.out.println(brothers.get(num - 1));
            }
        }
    }

    public static List<String> findBrothers(String[] strs, String str) {
        String orderStr = orderStrByChar(str);
        List<String> brothers = new ArrayList<>();
        for(String sub : strs) {
            // 同一个不是
            if(sub.equals(str)) {
                continue;
            }
            // 长度不一样不是
            if(sub.length() != str.length()) {
                continue;
            }
            // 排序后一样是
            String orderSub = orderStrByChar(sub);
            if(orderSub.equals(orderStr)) {
                brothers.add(sub);
            }
        }
        if (!brothers.isEmpty()) {
            Collections.sort(brothers);
        }
        return brothers;
    }

    /**
     * 将字符串先排序
     * @param str
     * @return
     */
    private static String orderStrByChar(String str) {
        List<Character> strChars = new ArrayList<>();
        for(char c : str.toCharArray()) {
            strChars.add(c);
        }

        Collections.sort(strChars, new Comparator<Character>() {
            @Override
            public int compare(Character o1, Character o2) {
                if(o2.compareTo(o1) < 0) {
                    return 1;
                }
                return -1;
            }
        });
        StringBuilder sb = new StringBuilder();
        for (char c : strChars) {
            sb.append(c);
        }
        return sb.toString();
    }
}
